package com.geniusk.app.controller;

import com.geniusk.common.core.JSONResult;
import com.geniusk.common.utils.VideoUtil;
import com.geniusk.file.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * APP聊天接口
 */
@RestController
@RequestMapping("/app/chat")
public class AppChatController {


    @Autowired
    private MinioUtil minioUtil;

    /**
     * 聊天图片上传
     */
    @PostMapping("/uploadChatPhoto")
    public JSONResult uploadChatPhoto(@RequestParam("file") MultipartFile file) {
        String contentType = file.getContentType();
        long fileSize = file.getSize();
        if(fileSize / 1024 / 1024 > 10){
            return JSONResult.errorMsg("上传聊天图片大小不能超过10MB");
        }
        assert contentType != null;
        if(!contentType.equals("image/jpeg") && !contentType.equals("image/png")){
            return JSONResult.errorMsg("上传聊天图片只能是图片格式");
        }
        try {
            String imageUrl = minioUtil.uploadFile(file);
            Map<String,Object> result = new HashMap<>();
            result.put("imageUrl", imageUrl);
            return JSONResult.ok(result);
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 聊天视频上传
     */
    @PostMapping("/uploadChatVideo")
    public JSONResult uploadChatVideo(@RequestParam("file") MultipartFile multipartFile) {
        String contentType = multipartFile.getContentType();
        long fileSize = multipartFile.getSize();
        if(fileSize / 1024 / 1024 > 100){
            return JSONResult.errorMsg("上传聊天视频大小不能超过100MB");
        }
        assert contentType != null;
        try {
            String videoUrl = minioUtil.uploadFile(multipartFile);
            if (null != videoUrl) {
                // 获得第一帧
                byte[] b = VideoUtil.getVideoFirstFrame(videoUrl);
                // 获得封面原理，通过使用ffmpeg截帧，获取第一帧
                String coverUrl = minioUtil.uploadVideoCover(b);
                Map<String, Object> result = new HashMap<>();
                result.put("videoUrl",videoUrl);
                result.put("coverUrl",coverUrl);
                return JSONResult.ok(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return JSONResult.errorMsg("视频上传错误");
    }
}
